﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using System.Collections;
using Spring.Context;
using System.IO;
using Spring.Context.Support;
using Common.Logging;

namespace BMS.Syncro.Devices.Host
{
    public class Controller
    {
        #region Properties
        private readonly ILog _log = null;
        public IApplicationContext IoC { get; private set; }
        #endregion Properties

        #region Methods
        public Controller()
        {
            _log = LogManager.GetLogger(this.GetType());
        }

        /// <summary>
        /// Start the service with TopShelf and load the Spring .NET context
        /// </summary>
        public void Start()
        {
            try
            {
                _log.Info("Iniciando el servicio de sincronización.");
                IoC = ContextRegistry.GetContext();
                CreateQueues();
                _log.Info("El servicio de sincronización se ha iniciado satisfactoriamente.");
            }
            catch (Exception ex)
            {
                _log.Fatal("Error fatal al inicializar el servicio de sincronización.", ex);
                Console.WriteLine(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Stop the service with TopShelf and stop the Spring .NET context
        /// </summary>
        public void Stop()
        {
            try
            {
                ((XmlApplicationContext)IoC).Stop();
                _log.Info("El servicio de sincronización de dispositivos biométricos se ha detenido");
            }
            catch (Exception e)
            {
                _log.Fatal(string.Format("Error al detener el servicio. {0}", e));
                Environment.Exit(0);
            }
        }

        /// <summary>
        /// Create automatically queue in the MessageQueue of Windows
        /// </summary>
        private void CreateQueues()
        {
            // Reading the queues
            var queues = IoC.GetObjectsOfType(typeof(MessageQueue)).Cast<DictionaryEntry>().Select(x => x.Value).Cast<MessageQueue>();

            foreach (var queue in queues)
            {
                try
                {
                    if (!MessageQueue.Exists(queue.Path))
                    {
                        MessageQueue.Create(queue.Path, true);
                    }
                }
                catch (Exception exception)
                {
                    var strMsg = string.Format("No fue posible realizar la validación de la cola: [{0}] debido a: {1}", queue.Path, exception.Message);
                }
            }
        }
        #endregion Methods
    }
}
